(function($){
    var sourceData = null;
    var casecade = {
        createOptions: function(curSelect, index){
            if(curSelect.length == 0){
                return false;
            }
            var wrap = this,
                settings = wrap.data('cascade'),
                prevSelect = curSelect.prev(),
                urlObj = null;

            if(!settings.urls){
                return false;
            }

            if($.isArray(settings.urls)){
                urlObj = settings.urls[index]
            }else{
                urlObj = settings.urls;
            }

            var datas = {};
            datas　=　urlObj.onSetParam && urlObj.onSetParam.call(curSelect, prevSelect);
            var ajaxOption = $.extend({}, settings.ajaxOption, {
                type : 'POST',
                dataType : 'json',
                url : urlObj.url,
                data: datas,
                success: function(json){
                    casecade.generateOption({
                        curSelect: curSelect,
                        index: index,
                        data: json.data,
                        wrap: wrap,
                        settings: settings
                    });

                }
            });

            $.ajax(ajaxOption);
        },

        generateOption: function(option){
            var curSelect = option.curSelect,
                index = option.index,
                data = option.data,
                wrap = option.wrap,
                settings = option.settings;

            if(curSelect.length == 0){
                return false;
            }
            curSelect.find('option:gt(0)').remove();

            //var data = json.data;
            if(data && data.length > 0){
                var selectStr = '',
                    fieldSettings = settings;
                if(!settings.source){
                    if($.isArray(settings.urls)){
                        fieldSettings = settings.urls[index];
                    }else{
                        fieldSettings = settings.urls;
                    }
                }
                $.each(data, function(i){
                    var obj = this,
                        value = obj[fieldSettings.valueField],
                        text = obj[fieldSettings.textField];
                    selectStr += '<option value="'+value+'">'+text+'</option>';
                });
                curSelect.append(selectStr);

                curSelect.show();

                if(settings.defaultValues){
                    var defaultVal = settings.defaultValues[index];
                    if(defaultVal){
                        curSelect.val(defaultVal);
                        curSelect.trigger("change");
                    }

                    // 最后一个清除默认配置
                    if(settings.defaultValues.length == index+1){
                        settings.defaultValues = null;
                    }
                }
            }else{
                curSelect.hide();
            }

            // 创建下拉列表完成回调
            settings.onRender(curSelect);
        },

        setSelectChange: function(wrap){
            var methods = this,
                settings = wrap.data('cascade');

            //methods.resetSelect(wrap.find("select:eq(0)"));
            wrap.off().on("change", "select", function(){
                // 查找下一级
                var self = $(this),
                    nextSelect = self.next();
                index = wrap.find("select").index(nextSelect);



                methods.resetSelect(self);

                // 创建下级下拉列表框
                var curSelectVal = self.val();
                if(settings.source){
                    if(curSelectVal){
                        casecade.generateOption({
                            curSelect: nextSelect,
                            index: index,
                            data: sourceData[curSelectVal],
                            wrap: wrap,
                            settings: settings
                        });
                    }
                }else{
                    casecade.createOptions.call(wrap, nextSelect, index, curSelectVal);
                }

                settings.onChange.call(self, index-1);

            });
        },

        generateSelectBySource: function(wrap){
            var methods = this,
                settings = wrap.data('cascade');

            sourceData = {};
            casecade.handlerData(settings.source, 0);
            // console.log(sourceData);
            var firstSelect = wrap.find('select').eq(0);
            casecade.generateOption({
                curSelect: firstSelect,
                index: 0,
                data: sourceData[0],
                wrap: wrap,
                settings: settings
            });
        },

        handlerData: function(data, parentId){
            if(data){
                var tempArray = [];
                $.each(data, function(i, item){
                    tempArray.push(item);
                    sourceData[parentId] = tempArray;
                    if(item['childrenCategory']){
                        casecade.handlerData(item['childrenCategory'], item.id);
                    }
                });
            }
        }
    };

    var methods = {

        // urls参数可为对象也可为数组，必有项为
        //    url:'',
        //    textField: 'areaName',
        //    valueField: 'id',
        //    onSetParam: function
        init: function(options) {
            return this.each(function() {
                var wrap = $(this);
                var settings = wrap.data('cascade');

                if(typeof(settings) == 'undefined') {
                    var defaults = {
                        urls: [{
                            url:'',
                            onSetParam: $.noop,
                            textField:'name',
                            valueField: 'id'
                        }], // 数组或对象
                        ajaxOption: null,

                        source: null,
                        childrenFieldName:'',
                        textField:'name',
                        valueField: 'id',

                        defaultValues: null, // 是个数组
                        onRender: $.noop,
                        onChange: $.noop
                    };

                    settings = $.extend(true, {}, defaults, options);
                    wrap.data('cascade', settings);
                }

                casecade.setSelectChange.call(methods, wrap);

                if(settings.source){
                    casecade.generateSelectBySource.call(methods, wrap);
                }else{
                    var firstSelect = wrap.find('select').eq(0);
                    casecade.createOptions.call(wrap, firstSelect, 0);
                }



            });
        },

        // 重置某个下拉列表框之后的所有下拉列表
        resetSelect: function(select){
            select.next().nextAll("select").hide();
            select.nextAll("select").each(function(index){
                $(this).find("option:gt(0)").remove();
            });
        }
    };

    $.fn.cascade = function() {
        var method = arguments[0];

        if(methods[method]) {
            method = methods[method];
            arguments = Array.prototype.slice.call(arguments, 1);
        } else if( typeof(method) == 'object' || !method ) {
            method = methods.init;
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.cascade' );
            return this;
        }

        return method.apply(this, arguments);

    }

})(window.$);
